package com.stormragetech.teamwork.spring.dao;

import com.stormragetech.common.exception.StormragetechException;
import com.stormragetech.teamwork.common.constant.Constants;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.Assert;

import java.util.List;

/**
 * description: //TODO
 *
 * @author: Xue Bin
 * @version: 1.0.0-SNAPSHOT
 */
public abstract class MongoDao<T> {

    private final MongoTemplate template;

    public MongoDao(MongoTemplate template) {
        Assert.notNull(template, "MongoTemplate cannot be null !!!");
        this.template = template;
    }

    protected void insert(final T t, final String col) throws StormragetechException {

        try {
            template.insert(t, col);

        } catch (Exception e) {
            throw new StormragetechException(Constants.DAO_ERR_CODE, e.getMessage(), e);
        }
    }

    protected T findOne(final Query query, final String col, final Class<T> className) throws StormragetechException {

        try {
            return template.findOne(query, className, col);

        } catch (Exception e) {
            throw new StormragetechException(Constants.DAO_ERR_CODE, e.getMessage(), e);
        }
    }

    protected List<T> findAll(final String col, final Class<T> className) throws StormragetechException {

        try {
            return template.findAll(className, col);

        } catch (Exception e) {
            throw new StormragetechException(Constants.DAO_ERR_CODE, e.getMessage(), e);
        }
    }

    protected List<T> findList(final Query query, final String col, final Class<T> className) throws StormragetechException {

        try {
            return template.find(query, className, col);

        } catch (Exception e) {
            throw new StormragetechException(Constants.DAO_ERR_CODE, e.getMessage(), e);
        }
    }

}
